from PySide6.QtCore import Qt, QThread, Signal, QPoint, QRect, QLocale, QTranslator, QCoreApplication, QThreadPool, \
    QObject, QRunnable
from PySide6.QtGui import QCursor, QPixmap, QIcon, QFont
from PySide6.QtWidgets import QApplication, QMessageBox, QListWidget, QDialog, QVBoxLayout, QPushButton, QCheckBox, \
    QWidget, QScrollArea, QLabel, QHBoxLayout, QTableWidget, QTableWidgetItem
from gui.about_view import Ui_AboutWindow
from gui.main_view import Ui_MainWindow
from packaging import version
import webbrowser
import subprocess
import img_res  # skipcq: PYL-W0611
import json
import sys
from utils.handle import resource_path
from utils.handle import get_dir_size
import logging
import sys
import os
from pathlib import Path
from WinUninstaller import WinUninstaller
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
# 版本号
__version__ = "1.12.0"


class Logic:
    # 初始化
    def __init__(self):
        about.label_version.setText(QCoreApplication.translate("Label", "Version") + f" {__version__}")
        self.uninstaller = WinUninstaller()
        self.total_size = 0
        self.is_link_menu = False
        self.main_title = QCoreApplication.translate("Label",
                                                     "Select the default Windows 10 apps to uninstall:\n(Hover over app names to view description)")
        # 商店菜单视图的标题文本，提示点击应用名称在 Microsoft Store 中查看
        self.store_title = QCoreApplication.translate("Label", "Click on an app name to view it in Microsoft Store.")
        self.refresh_title = QCoreApplication.translate("Label", "Refreshing list of installed apps...")
        self.size_text = QCoreApplication.translate("Label", "MB")
        # 询问是否访问 GitHub 页面的对话框文本
        self.github_dialog = QCoreApplication.translate("MessageBox", "Visit the Efficient Uninstall GitHub page?")
        self.quit_dialog = QCoreApplication.translate("MessageBox", "Quit Efficient Uninstall?")
        self.dialog_yes = QCoreApplication.translate("Button", "Yes")
        self.dialog_no = QCoreApplication.translate("Button", "No")
        self.dialog_ok = QCoreApplication.translate("Button", "OK")
        self.success_text = QCoreApplication.translate("MessageBox", "All selected apps were successfully uninstalled.")
        # 主界面的主要控件列表
        self.main_widgets = (
            ui.refresh_btn, ui.refresh_bind, ui.store_btn, ui.store_bind, ui.button_select_all, ui.button_deselect_all,
            ui.button_uninstall)
        # 应用字典，存储应用的相关信息
        self.apps_dict = ui.apps_dict

        ui.progressbar.setValue(0)
        ui.progressbar.setMaximum(len(self.apps_dict))
        ui.progressbar.setFont(ui.font)
        ui.layout_widget_labels.adjustSize()
        # 遍历复选框布局，添加拉伸项并设置间距
        for layout in (ui.layout_checkboxes, ui.layout_checkboxes_2, ui.layout_checkboxes_3):
            layout.addStretch()
            layout.setSpacing(14)
        # 调整复选框布局所在的控件大小
        for layout_widget in (
                ui.layout_widget_checkboxes, ui.layout_widget_checkboxes_2, ui.layout_widget_checkboxes_3):
            layout_widget.adjustSize()
        # 为按钮绑定方法
        ui.button_uninstall.clicked.connect(self.uninstall)
        ui.button_select_all.clicked.connect(self.select_all)
        ui.button_deselect_all.clicked.connect(self.deselect_all)
        ui.refresh_btn.clicked.connect(self.app_refresh)
        ui.refresh_bind.activated.connect(self.app_refresh)
        ui.store_btn.clicked.connect(self.store_menu)
        ui.store_bind.activated.connect(self.store_menu)
        ui.homepage_btn.clicked.connect(self.app_homepage)
        ui.homepage_bind.activated.connect(self.app_homepage)
        ui.about_btn.clicked.connect(self.app_about)
        ui.about_bind.activated.connect(self.app_about)
        ui.quit_btn.clicked.connect(self.app_quit)
        ui.quit_bind.activated.connect(self.app_quit)
        about.button_quit_about.clicked.connect(about.close)
        # 为每个复选框的点击事件绑定启用按钮方法
        for checkbox in ui.checkbox_list:
            checkbox.clicked.connect(self.enable_buttons)

        # 刷新
        self.app_refresh()

    def store_menu(self):
        """
        切换主视图和商店视图。
        """
        logger.info(f"Switching to {'store' if self.is_link_menu else 'main'} view.")
        widgets = (ui.layout_widget_buttons, ui.label_space, ui.label_size)
        # 如果当前处于商店菜单视图
        if self.is_link_menu:
            self.is_link_menu = False
            ui.label_info.setText(self.main_title)
            ui.store_btn.setIcon(QIcon(':/icon/store_icon.png'))
            for i in self.apps_dict:
                i.setEnabled(False)
                i.setChecked(False)
            for i in self.installed_apps:
                i.setEnabled(True)
            for i in self.selected_apps:
                i.setChecked(True)
            self.enable_buttons()
            for widget in widgets:
                widget.show()
        else:
            self.is_link_menu = True
            ui.label_info.setText(self.store_title)
            ui.store_btn.setIcon(QIcon(':/icon/back_icon.png'))
            for i in self.apps_dict:
                i.setEnabled(True)
                i.setChecked(True)
            for widget in widgets:
                widget.hide()

    def show_updates(self, latest_version):
        """
        显示更新信息。
        :param latest_version: 最新版本号
        """
        # 比较最新版本号和当前版本号
        if version.parse(latest_version) > version.parse(__version__):
            msg_update = QCoreApplication.translate("MessageBox",
                                                    "Efficient Uninstall {0} is available.\n\nVisit download page?").format(
                latest_version)
            if self.message_box(msg_update, 2) == QMessageBox.Yes:
                # 获取最新的github地址
                # webbrowser.open_new('github地址')

    def app_refresh(self):
        """
        创建线程来刷新已安装应用的列表。
        """
        logger.info("Refreshing installed apps list...")
        # 如果当前处于商店菜单视图，切换到主视图
        if self.is_link_menu:
            self.store_menu()
        # 清空已安装应用列表
        self.installed_apps = []
        # 初始化进度为 0
        self.progress = 0
        # 禁用所有应用复选框并取消选中
        for i in self.apps_dict:
            i.setEnabled(False)
            i.setChecked(False)
        ui.label_refresh.show()
        ui.label_info.hide()
        # 显示进度条
        ui.progressbar.show()
        # 禁用主界面的主要控件
        for widget in self.main_widgets:
            widget.setEnabled(False)
        # 设置鼠标光标为忙碌状态
        QApplication.setOverrideCursor(QCursor(Qt.BusyCursor))

        ui.label_refresh.setText(self.refresh_title)
        logger.info("Started refreshing the apps list")
        self.check_thread = CheckApps(self.apps_dict)
        # 将线程的应用信号连接到启用已安装应用复选框的方法
        self.check_thread.app_signal.connect(self.enable_installed)
        # 将线程的进度信号连接到更新进度条的方法
        self.check_thread.progress_signal.connect(self.update_progress)
        self.check_thread.start()

    def thread_finished(self):
        """
        任务完成后设置主视图。
        """
        # 隐藏进度条
        ui.progressbar.hide()
        ui.label_refresh.hide()
        ui.label_info.show()
        ui.progressbar.setValue(0)
        QApplication.setOverrideCursor(QCursor())
        ui.label_info.setText(self.main_title)
        # 启用刷新和商店相关的按钮
        for widget in (ui.refresh_btn, ui.refresh_bind, ui.store_btn, ui.store_bind):
            widget.setEnabled(True)
        logger.info("Uninstallation process completed.")
        self.enable_buttons()

    def enable_installed(self, i):
        """
        刷新已安装应用列表时启用复选框。
        :param i: 应用的复选框控件
        """
        # 启用复选框
        i.setEnabled(True)
        # 将复选框添加到已安装应用列表中
        self.installed_apps.append(i)
        self.enable_buttons()

    def update_progress(self):
        """
        刷新已安装应用列表时更新进度条。
        """
        # 进度加 1
        self.progress += 1
        ui.progressbar.setValue(self.progress)
        if self.progress >= len(self.apps_dict):
            # 执行任务完成后的操作
            self.thread_finished()

    def uninstall_progress(self, i):
        """
        卸载所选应用时更新进度条和标签。
        :param i: 应用的复选框控件
        """
        self.progress += 1
        ui.progressbar.setValue(self.progress)
        # 从已安装应用列表中移除该应用
        self.installed_apps.remove(i)
        app_name = i.text().replace(' && ', ' & ')
        # 计算还剩余多少个应用待卸载
        apps_left = len(self.selected_apps) - self.progress + 1
        ui.label_refresh.setText(
            QCoreApplication.translate("Label", "Uninstalling {0}, %n app(s) left...", "", apps_left).format(app_name))
        logger.info(f"Uninstalling app {app_name}, {apps_left} apps remaining.")
        ui.label_refresh.show()
        # 如果进度达到所选应用的数量，说明卸载完成
        if self.progress >= len(self.selected_apps):
            self.thread_finished()
            logger.info("Uninstallation complete.")
            self.message_box(self.success_text)

    def enable_buttons(self):
        """
        点击复选框时启用按钮或打开 Microsoft Store。
        """
        # 如果当前处于主视图
        if not self.is_link_menu:
            # 初始化已选应用
            self.total_size = 0
            self.selected_apps = []
            # 遍历已安装应用的复选框
            for i in self.installed_apps:
                if i.isChecked():
                    # 将该应用添加到已选应用列表中
                    self.selected_apps.append(i)
                    self.total_size += self.apps_dict[i]["size"]
                    # 更新显示总大小的标签文本
                    ui.label_size.setText(f'{self.total_size:.2f} {self.size_text}')
                    ui.layout_widget_labels.adjustSize()
            # 如果有任何已安装应用的复选框被选中
            if any(i.isChecked() for i in self.installed_apps):
                ui.button_uninstall.setDisabled(False)
                ui.button_deselect_all.setDisabled(False)
            else:
                ui.button_uninstall.setDisabled(True)
                ui.button_deselect_all.setDisabled(True)
                ui.label_size.setText(f'{self.total_size} {self.size_text}')

            if all(i.isChecked() for i in self.installed_apps):
                ui.button_select_all.setDisabled(True)
            else:
                ui.button_select_all.setDisabled(False)
        else:
            for i in self.apps_dict:
                if not i.isChecked():
                    i.setChecked(True)
                    # 打开该应用在 Microsoft Store 中的页面
                    webbrowser.open_new(f'ms-windows-store://pdp{self.apps_dict[i]["link"]}')

    def message_box(self, message: str, buttons: int = 1) -> int:
        """
        显示带有 "是/否" 或者 "确定" 按钮的消息框，默认显示 "确定" 按钮。
            参数:
                message (str): 消息框内显示的消息内容。
                buttons (int): 按钮的数量，1 表示显示 "确定" 按钮，2 表示显示 "是/否" 按钮。
            返回值:
                choice (int): 用户点击的按钮的 ID。
        """
        pixmap = QPixmap(resource_path('icon.ico')).scaledToWidth(35, Qt.SmoothTransformation)
        msg_box = QMessageBox()
        msg_box.setFont(ui.font)
        msg_box.setText(message)
        if buttons == 2:
            msg_yes = msg_box.addButton(QMessageBox.Yes)
            msg_no = msg_box.addButton(QMessageBox.No)
            msg_yes.setText(self.dialog_yes)
            msg_no.setText(self.dialog_no)
            msg_yes.setProperty('class', 'button_yes')
            msg_no.setProperty('class', 'button_no')
        msg_box.setWindowFlags(Qt.Dialog | Qt.CustomizeWindowHint)
        msg_box.setIconPixmap(pixmap)
        with open(resource_path('style/style.css'), 'r') as file:
            msg_box.setStyleSheet(file.read())
        msg_box.move(ui.frameGeometry().center() - QRect(QPoint(), msg_box.sizeHint()).center())
        choice = msg_box.exec_()
        return choice

    @staticmethod
    def app_homepage():
        """显示已安装应用列表（在主窗口中切换显示）"""
        try:
            # 清除主窗口现有内容并准备显示应用列表
            ui.centralwidget.setVisible(False)  # 隐藏原有的中央控件
            
            # 如果应用列表控件不存在，则创建它
            if not hasattr(ui, 'app_list_widget'):
                ui.app_list_widget = QWidget(ui)
                ui.app_list_layout = QVBoxLayout(ui.app_list_widget)
                
                # 创建表格
                ui.app_table = QTableWidget()
                ui.app_table.setColumnCount(5)
                ui.app_table.setHorizontalHeaderLabels(["选择", "应用名称", "大小 (MB)", "安装日期", "安装路径"])
                ui.app_table.setSortingEnabled(True)
                ui.app_table.verticalHeader().setVisible(False)
                ui.app_table.setSelectionBehavior(QTableWidget.SelectRows)
                ui.app_table.setEditTriggers(QTableWidget.NoEditTriggers)
                
                # 设置列宽
                ui.app_table.setColumnWidth(0, 50)
                ui.app_table.setColumnWidth(1, 200)
                ui.app_table.setColumnWidth(2, 100)
                ui.app_table.setColumnWidth(3, 120)
                ui.app_table.setColumnWidth(4, 250)
                
                # 创建按钮容器
                button_container = QWidget()
                button_layout = QHBoxLayout(button_container)
                
                # 添加返回按钮
                back_btn = QPushButton("返回主界面")
                toggle_select_btn = QPushButton("全选")
                btn_uninstall = QPushButton("卸载选中")
                
                button_layout.addWidget(back_btn)
                button_layout.addWidget(toggle_select_btn)
                button_layout.addWidget(btn_uninstall)
                
                # 返回主界面功能
                def go_back_to_main():
                    ui.app_list_widget.setVisible(False)
                    ui.centralwidget.setVisible(True)
                
                back_btn.clicked.connect(go_back_to_main)
                
                # 全选/取消全选功能
                def toggle_select():
                    all_checked = all(
                        ui.app_table.cellWidget(row, 0).findChild(QCheckBox).isChecked()
                        for row in range(ui.app_table.rowCount())
                    )
                    new_state = not all_checked
                    for row in range(ui.app_table.rowCount()):
                        ui.app_table.cellWidget(row, 0).findChild(QCheckBox).setChecked(new_state)
                    toggle_select_btn.setText("取消全选" if new_state else "全选")
                
                toggle_select_btn.clicked.connect(toggle_select)
                
                # 卸载功能
                def perform_uninstall():
                    selected = []
                    for row in range(ui.app_table.rowCount()):
                        if ui.app_table.cellWidget(row, 0).findChild(QCheckBox).isChecked():
                            selected.append(ui.app_table.item(row, 1).data(Qt.UserRole))
                    
                    if not selected:
                        QMessageBox.warning(ui, "警告", "请先选择要卸载的程序")
                        return
                    
                    confirm = QMessageBox.question(
                        ui,
                        "确认卸载",
                        f"确定要卸载选中的 {len(selected)} 个程序吗？",
                        QMessageBox.Yes | QMessageBox.No
                    )
                    
                    if confirm == QMessageBox.Yes:
                        for prog in selected:
                            try:
                                # 执行卸载命令
                                subprocess.run(prog["uninstall_string"], shell=True, check=True)
                                
                                # 深度清理
                                reply = QMessageBox.question(
                                    ui, '深度清理',
                                    f'是否要对 {prog["name"]} 进行深度清理？',
                                    QMessageBox.Yes | QMessageBox.No
                                )
                                if reply == QMessageBox.Yes:
                                    logic.uninstaller.deep_clean(prog["name"])
                            except Exception as e:
                                QMessageBox.critical(ui, "错误", f"卸载 {prog['name']} 失败: {str(e)}")
                        
                        QMessageBox.information(ui, "完成", "卸载操作已完成")
                        # 刷新表格数据
                        refresh_app_list()
                
                btn_uninstall.clicked.connect(perform_uninstall)
                
                # 布局
                ui.app_list_layout.addWidget(ui.app_table)
                ui.app_list_layout.addWidget(button_container)
                
                # 样式设置
                ui.app_table.setStyleSheet("""
                    QTableWidget {
                        font-size: 12px;
                        selection-background-color: #E1F5FE;
                    }
                    QHeaderView::section {
                        background-color: #F5F5F5;
                        padding: 4px;
                    }
                """)
                
                # 将列表控件添加到主窗口
                ui.setCentralWidget(ui.app_list_widget)
            else:
                # 如果已经创建过，则重新显示
                ui.app_list_widget.setVisible(True)
            
            # 刷新应用列表数据
            def refresh_app_list():
                installed_programs = logic.uninstaller.get_installed_programs()
                
                # 清空表格
                ui.app_table.setRowCount(0)
                
                # 填充数据
                ui.app_table.setRowCount(len(installed_programs))
                for row, program in enumerate(installed_programs):
                    # 复选框
                    checkbox = QCheckBox()
                    checkbox_widget = QWidget()
                    checkbox_layout = QHBoxLayout(checkbox_widget)
                    checkbox_layout.addWidget(checkbox)
                    checkbox_layout.setAlignment(Qt.AlignCenter)
                    checkbox_layout.setContentsMargins(0, 0, 0, 0)
                    ui.app_table.setCellWidget(row, 0, checkbox_widget)
                    
                    # 名称
                    name_item = QTableWidgetItem(program["name"])
                    name_item.setData(Qt.UserRole, program)  # 存储完整数据
                    
                    # 大小
                    size_item = QTableWidgetItem()
                    size_item.setData(Qt.DisplayRole, round(program["actual_size"], 2))
                    
                    # 日期
                    date_item = QTableWidgetItem(program["install_date"])
                    
                    # 路径
                    path_item = QTableWidgetItem(program["install_location"] or "未知")
                    
                    ui.app_table.setItem(row, 1, name_item)
                    ui.app_table.setItem(row, 2, size_item)
                    ui.app_table.setItem(row, 3, date_item)
                    ui.app_table.setItem(row, 4, path_item)
                
                # 设置排序
                ui.app_table.setSortingEnabled(True)
                ui.app_table.sortByColumn(1, Qt.AscendingOrder)
            
            refresh_app_list()
            
        except Exception as e:
            print(f"获取应用列表时出错: {e}")
            QMessageBox.critical(None, "错误", f"无法获取应用列表: {str(e)}")
            # 发生错误时返回主界面
            ui.centralwidget.setVisible(True)

    @staticmethod
    def app_about():
        """展示app窗口"""
        about.setWindowModality(Qt.ApplicationModal)
        about.move(ui.geometry().center() - about.rect().center())
        about.show()

    def app_quit(self):
        """确认退出"""
        if self.message_box(self.quit_dialog, 2) == QMessageBox.Yes:
            app.quit()

    def select_all(self):
        """选择全部"""
        for i in self.installed_apps:
            if not i.isChecked():
                i.setChecked(True)
        self.enable_buttons()

    def deselect_all(self):
        """取消全选."""
        for i in self.installed_apps:
            if i.isChecked():
                i.setChecked(False)
        self.enable_buttons()

    def uninstall(self):
        """Create threads to uninstall selected apps after confirmation."""
        apps = len(self.selected_apps)
        confirm_uninstall = QCoreApplication.translate("MessageBox", "Uninstall %n app(s)?", "", apps)
        space_freed_text = QCoreApplication.translate("MessageBox", "MB of space will be freed.")
        msg_uninstall = f"{confirm_uninstall}\n\n{self.total_size:.2f} {space_freed_text}"

        if self.message_box(msg_uninstall, 2) == QMessageBox.Yes:
            logger.info(f"用户确认卸载以下应用：{[i.text() for i in self.selected_apps]}")
            for widget in self.main_widgets:
                widget.setEnabled(False)
            ui.label_info.hide()
            self.progress = 0
            ui.progressbar.setMaximum(apps)
            ui.progressbar.show()

            self.new_thread_list = []
            for item, i in enumerate(self.selected_apps):
                i.setEnabled(False)
                i.setChecked(False)
                self.new_thread_list.append(UninstallApps(self.apps_dict, i))
                self.new_thread_list[item].signals.progress_signal.connect(self.uninstall_progress)
            self.newPoolThread = RunThreadPool(self.new_thread_list)
            self.newPoolThread.start()


class CheckApps(QThread):
    """ 刷新下载列表"""
    progress_signal = Signal()
    app_signal = Signal(object)

    def __init__(self, apps_dict):
        super().__init__()
        self.apps_dict = apps_dict

    def run(self):
        # 设置 PowerShell 执行参数
        si = subprocess.STARTUPINFO()
        si.dwFlags |= subprocess.STARTF_USESHOWWINDOW

        # 执行 PowerShell 命令获取已安装应用的列表
        x = subprocess.Popen(
            ["powershell", "Get-AppxPackage -PackageTypeFilter Main | Select Name, InstallLocation | ConvertTo-JSON"],
            stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False, startupinfo=si,
            text=True)

        # 获取命令输出
        names_str, stderr = x.communicate()

        # 如果输出为空，输出错误信息并终止函数
        if not names_str:
            # print("PowerShell 命令执行结果为空，可能命令执行失败。")
            # print(f"错误信息：{stderr}")
            logger.error(f"获取已安装应用列表失败，PowerShell返回空结果,错误信息：{stderr.strip()}")
            return

        try:
            # 尝试将输出解析为 JSON
            names_list = json.loads(names_str)
        except json.JSONDecodeError as e:
            # print(f"JSONDecodeError: {e}")
            # print("返回的字符串:", names_str)
            logger.error("JSON解析异常详情，原始返回内容：%s", names_str)
            return  # 退出函数，避免后续错误

        # 遍历应用字典处理每个应用的大小
        for i in self.apps_dict:
            temp_name = self.apps_dict[i]["name"].strip("*")
            self.apps_dict[i]["size"] = 0
            flag = False
            if temp_name != "Xbox":
                for item in names_list:
                    name = item["Name"]
                    if name.find(temp_name, 0, len(name)) != -1:
                        flag = True
                        self.apps_dict[i]["size"] += get_dir_size(item["InstallLocation"]) / 1024 / 1024
                        break
            else:
                for item in names_list:
                    name = item["Name"]
                    if name.find(temp_name, 0, len(name)) != -1 and name.find("XboxGameCallableUI", 0, len(name)) == -1:
                        flag = True
                        self.apps_dict[i]["size"] += get_dir_size(item["InstallLocation"]) / 1024 / 1024

            # 如果找到匹配的应用，发出信号
            if flag:
                self.app_signal.emit(i)

            # 更新进度
            self.progress_signal.emit()


class RunThreadPool(QThread):
    """运行线程池来卸载选中的应用。"""

    def __init__(self, new_thread_list):
        super().__init__()
        self.new_thread_list = new_thread_list

    def run(self):
        pool = QThreadPool()
        for new_thread in self.new_thread_list:
            pool.start(new_thread)
        pool.waitForDone()


class UninstallSignals(QObject):
    """用于卸载应用时发射 PyQt 信号的类。"""
    progress_signal = Signal(object)


class UninstallApps(QRunnable):
    """卸载选中的应用。"""
    def __init__(self, apps_dict, i):
        super().__init__()
        self.signals = UninstallSignals()
        self.apps_dict = apps_dict
        self.i = i

    def run(self):
        package_name = self.apps_dict[self.i]["name"]
        logger.info(f"开始卸载应用: {package_name}")
        if "Xbox" in package_name:
            package_name = "*Xbox* | Where-Object {$_.name -notmatch 'XboxGameCallableUI'}"
        si = subprocess.STARTUPINFO()
        si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        x = subprocess.Popen(
            ["powershell",
             f'try {{Get-AppxPackage {package_name} -OutVariable app | Remove-AppPackage -ea stop;[bool]$app}} catch {{$false}}'],
            stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=False, startupinfo=si
        )
        x.communicate()[0]
        self.signals.progress_signal.emit(self.i)


if __name__ == '__main__':
    # 日志配置
    logger.info("Initializing the application...")

    QApplication.setAttribute(Qt.AA_EnableHighDpiScaling, True)
    QApplication.setHighDpiScaleFactorRoundingPolicy(Qt.HighDpiScaleFactorRoundingPolicy.PassThrough)
    app = QApplication(sys.argv)
    app.setFont(QFont("Tahoma"))
    # 加载多语言环境
    locale = QLocale() #自动获取系统的语言环境
    trans = QTranslator()
    if trans.load(locale, "", "", resource_path("Language"), ".qm"):
        app.installTranslator(trans)
    about = Ui_AboutWindow()
    about.setupUi()
    ui = Ui_MainWindow()
    ui.setupUi()
    ui.show()
    logic = Logic()
    sys.exit(app.exec_())
    logger.info("Initialization complete.")
